package error

import (
	"com.cyt.common/constant"
	"com.cyt.common/library/webhook"
	"fmt"
	"github.com/gogf/gf/errors/gerror"
	"github.com/gogf/gf/frame/g"
	"github.com/gogf/gf/net/ghttp"
	"github.com/gogf/gf/os/gtime"
	"github.com/gogf/gf/text/gstr"
	"github.com/gogf/gf/util/gconv"
	"os/exec"
)

func ErrorNotify(r *ghttp.Request) {
	// 请求信息
	requestInfo := fmt.Sprintf(
		`%d "%s %s %s" %s, %s, "%s"`,
		r.Response.Status, r.Method, r.Host, r.URL.Path,
		gtime.Datetime(), r.GetClientIp(), r.UserAgent(),
	)
	// 请求参数
	requestParam := gconv.String(r.GetRequestMap())
	// Debug信息
	stackData := gerror.Stack(r.GetError())
	stackLines := gstr.Explode("\n", stackData)
	var stackFile, fileLine string
	for i := 0; i < len(stackLines); i++ {
		if gstr.Contains(stackLines[i], constant.APP_PATH) && gstr.Contains(stackLines[i], ":") {
			stackInfo := gstr.Explode(":", gstr.Replace(stackLines[i], " ", ""))
			stackFile = gstr.TrimAll(stackInfo[0], " ")
			fileLine = stackInfo[1]
			break;
		}
	}
	// 获取GIT信息
	cmd := exec.Command("git", "blame", "-L", fileLine+","+fileLine, gstr.TrimAll(stackFile, " "))
	stdout, _ := cmd.CombinedOutput()
	gitInfo := gstr.Explode("       ", string(stdout))[0]
	// 企业微信推送
	webhook.Wecom.Send("https://qyapi.weixin.qq.com/cgi-bin/webhook/send?key=8e070741-e26a-4916-9d68-d70f1415cc0b", map[string]interface{}{
		"msgtype": "markdown",
		"markdown": g.Map{
			"content": "<font color='warning'>电霸公共服务异常告警</font>\n" +
				"> " + "请求信息: <font color='black' style='white-space:pre;'>" + requestInfo + "</font>" + "\n" +
				"> " + "请求参数: <font color='grey' style='white-space:pre;'>" + requestParam + "</font>\n" +
				"> " + "报错信息: <font color='red' style='white-space:pre;'>" + gconv.String(r.GetError()) + "</font>\n" +
				"> " + "报错文件: <font color='grey' style='white-space:pre;'>" + stackFile + ":" + fileLine + "</font>\n" +
				"> " + "GIT信息: <font color='red' style='white-space:pre;'>" + gitInfo + "</font>\n",
		},
	})
}
